package raffle

import (
	"math/rand"
	"time"
)

// Prize 结构体定义奖品，包括名称、权重、概率和库存
type Prize struct {
	Name   string
	Weight int
	Stock  int
}

// Lottery 结构体定义抽奖系统
type Lottery struct {
	Prizes []Prize
}

// NewLottery 初始化抽奖系统
func NewLottery(prizes []Prize) *Lottery {
	return &Lottery{Prizes: prizes}
}

// Draw 抽奖方法
func (l *Lottery) Draw() (string, bool) {
	rand.Seed(time.Now().UnixNano()) // 确保每次运行生成的随机数不同

	totalWeight := 0
	for _, prize := range l.Prizes {
		if prize.Stock > 0 {
			totalWeight += prize.Weight
		}
	}

	if totalWeight == 0 {
		return "No Prizes Available", false
	}

	randNum := rand.Intn(totalWeight) // 生成随机数

	cumulativeWeight := 0
	for _, prize := range l.Prizes {
		if prize.Stock > 0 {
			cumulativeWeight += prize.Weight
			if randNum < cumulativeWeight {
				// 检查库存
				if prize.Stock > 0 {
					//这块改成mysql减库存
					prize.Stock-- // 更新库存
					return prize.Name, true
				}
			}
		}
	}
	return "No Prize", false
}
